package com.fc.system.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fc.framework.BusinessException;
import com.fc.system.service.ExcelReader;

public abstract class AbstractExcelReader implements ExcelReader {

    private static final Logger logger = LoggerFactory.getLogger(AbstractExcelReader.class);

    @Override
    public Map<Integer, String> read(String filePath) {
        Workbook wb = null;
        try {
            wb = new XSSFWorkbook(OPCPackage.open(filePath));
        } catch (Exception e) {
            logger.error("Load excel file error!", e);

            throw new BusinessException("上传文件错误!");
        }

        Map<Integer, String> msg = new HashMap<Integer, String>();

        Sheet sheet = wb.getSheetAt(0);
        if (sheet == null || sheet.getLastRowNum() < 1) {
            throw new BusinessException("第一个sheet为空!");
        }

        validateExcel(sheet);

        int index = 1;
        boolean isReadOver = false;
        do {
            try {
                Row row = sheet.getRow(index++);

                if (row == null) {
                    isReadOver = true;
                } else {
                    isReadOver = readRow(row, index);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                msg.put(index, e.getMessage());
            }
        } while (!isReadOver);

        return msg;
    }

    /**
     * 
     * @param row
     * @param index
     * @return 是否读取完毕
     */
    protected abstract boolean readRow(Row row, int index);

    protected abstract void validateExcel(Sheet sheet);
}